//
//  HMStatusCellViewModel.swift
//  WeiBo
//
//  Created by Feng on 2017/6/8.
//  Copyright © 2017年 feng. All rights reserved.
//


import UIKit
import YYText

class HMStatusCellViewModel: NSObject {

    //cell模型
    var status: HMStatus?
    {
        didSet {
            
            guard let currentStatus = status else
            {
                return
            }
            //处理等级图片
            handleMbrankImage(mbrnk: currentStatus.user?.mbrank ?? 0)
            //处理认证图片
            handleVerifiedImage(verified: currentStatus.user?.verified_type ?? -1)
            //拼接转发微博内容
            handleRetweetContent(Content: currentStatus.retweeted_status?.text, userName: currentStatus.retweeted_status?.user?.screen_name)
            //截取来源文字
            handleSourceTitle(title: currentStatus.source ?? "")
            //转发,评论,赞的数量
            handleRepostsCount(reposts: currentStatus.reposts_count)
            handleCommentsCount(comments: currentStatus.comments_count)
            handleAttitudesCount(attitudes: currentStatus.attitudes_count)
            //发布时间-->自己写,暂不使用
//            handleCreateTime(time: currentStatus.created_at)
            originalAttributedText = handleOriginalAttributedText(originalText: currentStatus.text ?? "", isOriginal: true)
        }
    }
    
    //会员等级图片
    var mbrankImage: UIImage?
    //认证等级图片
    var verifiedImage: UIImage?
    //拼接转发微博内容
    var reweetContent: String?
    //截取来源文字
    var sourceTitle: String?
    //转换转发数
    var repostsCount: String?
    //转换评论数
    var commentsCount: String?
    //赞数
    var attitudesCount : String?
    
    //  原创微博富文本
    var originalAttributedText: NSAttributedString?
    // 转发微博富文本
    var retweetAttributedText: NSAttributedString?
    
    //将微博内容转成富文本
    private func handleOriginalAttributedText(originalText: String, isOriginal: Bool) -> NSAttributedString
    {
        //  把微博内容转成富文本
        let attributeText = NSMutableAttributedString(string: originalText)
        
        //  匹配微博内容中的表情描述
        let regularExpression = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: [])
        
        let matchesResultArray = regularExpression.matches(in: originalText, options: [], range: NSMakeRange(0, (originalText as NSString).length))
//        let matchesResultArray = regularExpression.matches(in: originalText, options: [], range: NSMakeRange(0, attributeText.length))
//        print((originalText as NSString).length,attributeText.length)
        
        //设置字体
        var fontSize: CGFloat = 14
        //设置颜色
        var color: UIColor = UIColor.darkGray
        if isOriginal == false {
            //  转发微博字体大小
            fontSize = 13
            color = UIColor.lightGray
        }

        
        //遍历匹配结果,获取表情数据的范围
        for matchesResult in matchesResultArray.reversed()
        {
            //  获取表情描述的范围
            let range = matchesResult.range
            // 根据范围获取内容
            let chs = (originalText as NSString).substring(with: range)
//            let chs = attributeText.attributedSubstring(from: range)
            //根据表情描述,查找对应的表情模型
            if let emoticon = HMEmoticonTools.sharedTools.searchEmoticonWithChs(chs: chs)
            {
                //  表示一定有表情模型
                let image = UIImage(named: emoticon.path!, in: EmoticonButton, compatibleWith: nil)!
                //  使用YYText 把图片转富文本 -->就不再需要分类方法 attributedStringWithEmoticon
                let emoticonAttributedText = NSAttributedString.yy_attachmentString(withEmojiImage: image, fontSize: fontSize)!
                //  根据表情模型创建表情富文本
//                let emoticonAttributedText = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: UIFont.systemFont(ofSize: fontSize))
                //  替换指定范围的表情富文本
                attributeText.replaceCharacters(in: range, with: emoticonAttributedText)
            }
            print(chs)
        }
        
        //  统一设置富文本的字体大小和文字文字颜色
        attributeText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: fontSize), NSForegroundColorAttributeName: color], range: NSMakeRange(0, attributeText.length))
        
        //  @xx:
        addHighlightedAttributedText(pattern: "@[^:]+", attributeText: attributeText)
        //  #xx#
        addHighlightedAttributedText(pattern: "#[^#]+#", attributeText: attributeText)
        //  http或者https
        addHighlightedAttributedText(pattern: "http[s]?://[^\\s\\u4e00-\\u9fa5]+", attributeText: attributeText)
        
        return attributeText
    }
        
        //富文本高亮显示
        //  pattern: 高亮的匹配的正则表达式
        //  attributedText: 微博富文本
        func addHighlightedAttributedText(pattern: String, attributeText: NSMutableAttributedString) {
        
            //使用正则表达式匹配高亮范围
            let highlightedRegularExpression = try! NSRegularExpression(pattern: pattern, options: [])
            //        let highlightedRegularExpression = try! NSRegularExpression(pattern: "@[^:\\s]+", options: [])
            
            //获取匹配结果
            let highlightedMatchResultArray = highlightedRegularExpression.matches(in: attributeText.string, options: [], range: NSMakeRange(0, (attributeText.string as NSString).length))
            //匹配遍历结果,获取高亮文字范围
            for highlightedMatchResult in highlightedMatchResultArray
            {
                //高亮文字范围
                let highlightedRange = highlightedMatchResult.range
                //  高亮文字颜色
                let color = UIColor(red: 80 / 255, green: 125 / 255, blue: 215 / 255, alpha: 1)
                //设置高亮范围富文本的颜色
                attributeText.addAttribute(NSForegroundColorAttributeName, value: color, range: highlightedRange)
                //创建文本高亮对象
                let textHighlight = YYTextHighlight()
                //高亮文字的背景色
                let bgColor = UIColor(red: 177 / 255, green: 215 / 255, blue: 255 / 255, alpha: 1)
                //创建文本边框对象
                let textBoarder = YYTextBorder(fill: bgColor, cornerRadius: 3)
                //设置边框的内间距
                textBoarder.insets = UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 0)
                //设置高亮的背景边框颜色
                textHighlight.setBackgroundBorder(textBoarder)
                //设置富文本的高亮文字的背景色，使用YYText的方法设置高亮
                attributeText.yy_setTextHighlight(textHighlight, range: highlightedRange)
            }
        }
    
    //发布时间
    //使用只读计算属性,每次使用都需要调用get方法,在get方法里面和当前时间进行比较
    var createTime: String?
    {
        get {
            guard let createAt = status?.created_at else {
                return nil
            }
            
            let dt = DateFormatter()
            
            if isThisYear(createAtDate: createAt)
            {
                //是今年
                //创建日历对象
                let calendar = Calendar.current
                if calendar.isDateInToday(createAt)
                {
                    let result = abs(createAt.timeIntervalSinceNow)
                    
                    if result < 60
                    {
                        return "刚刚"
                    }
                    else if result < 3600
                    {
                        let resultMin = result / 60
                        
                        return "\(Int(resultMin))分钟前"
                    }
                    else
                    {
                        let resultHour = result / 3600
                        
                        return "\(Int(resultHour))小时前"
                    }
                }
                else if calendar.isDateInYesterday(createAt)
                {
                    dt.dateFormat = "昨天 HH:mm"
                }
                else
                {
                    dt.dateFormat = "MM-dd HH:mm"
                }
            }
            else
            {
                //不是今年
                dt.dateFormat = "yyyy-MM-dd HH:mm"
            }
            
            return dt.string(from: createAt)
        }
    }
    
    //判断是否是今年
    private func isThisYear(createAtDate: Date) -> Bool
    {
        let dt = DateFormatter()
        dt.dateFormat = "yyyy"
        
        let createAtYear = dt.string(from: createAtDate)
        let currentYear = dt.string(from: Date())
        
        return createAtYear == currentYear
    }
    
    //设置发布时间
//    private func handleCreateTime(time: String?)
//    {
//        guard let crTime = time else {
//            return
//        }
//        
//        // 1.创建formatter
//        let formatter = DateFormatter()
//        
//        // 2.设置时间的格式
//        formatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"
//        
//        // 3. 设置时间的区域(真机必须设置，否则可能不会转换成功)
//        formatter.locale = Locale(identifier: "en")
//        
//        // 4.转换(转换好的时间是去除时区的时间)
//        let createdDate = formatter.date(from: crTime)!
//
//        let secondTime = Date().timeIntervalSince(createdDate)
//        
//        switch secondTime {
//        case _ where secondTime < 60:
//            createTime = "刚刚"
//        case _ where secondTime >= 60 && secondTime < 3600:
//            createTime = "\(Int(secondTime / 60))分钟前"
//        case _ where secondTime >= 3600 && secondTime < (3600 * 24):
//            createTime = "\(Int(secondTime / 3600))小时前"
//        //判断昨天,及其之前的日期
//        default:
//            let calendar = Calendar.current
//            let unitFlags: Set<Calendar.Component> = [Calendar.Component.year, Calendar.Component.month, Calendar.Component.day, Calendar.Component.hour, Calendar.Component.minute, Calendar.Component.second]
//            //当前日期的日历信息
//            let currentComp = calendar.dateComponents(unitFlags, from: Date())
//            let currentYear = String(currentComp.year ?? 0)
//            let currentMonth = String(currentComp.month ?? 0)
//
//            //微博创建日期的日历信息
//            let createComp = calendar.dateComponents(unitFlags, from: createdDate)
//            let createYear = String(createComp.year ?? 0)
//            let createMonth = String(createComp.month ?? 0)
//            let createDay = String(createComp.day ?? 0)
//            var createHour = String(createComp.hour ?? 0)
//            var createMinute = String(createComp.minute ?? 0)
//            
//            if createComp.hour ?? 0 < 10
//            {
//                createHour = "0" + createHour
//            }
//            
//            if createComp.minute ?? 0 < 10
//            {
//                createMinute = "0" + createMinute
//            }
//            
//            if currentYear == createYear
//            {
//                if (currentComp.day! - createComp.day! == 1) && (currentMonth == createMonth)
//                {
//                    createTime = "昨天 \(createHour):\(createMinute)"
//                }
//                else
//                {
//                    createTime = "\(createMonth)-\(createDay)"
//                }
//            }
//            else
//            {
//                createTime = "\(createYear)-\(createMonth)-\(createDay)"
//            }
//        }
//    }
    
    //转发数
    private func handleRepostsCount(reposts: Int)
    {
        repostsCount = handleCount(numType: "转发", numCount: reposts)
    }
    
    //评论数
    private func handleCommentsCount(comments: Int)
    {
        commentsCount = handleCount(numType: "评论", numCount: comments)
    }
    
    //赞数
    private func handleAttitudesCount(attitudes: Int)
    {
        attitudesCount = handleCount(numType: "转发", numCount: attitudes)
    }
    
    //转发,评论,赞的数量
    private func handleCount(numType: String, numCount: Int) -> String
    {
        var numStr: String?
        
        switch numCount {
        case _ where numCount <= 0:
            numStr = numType
        case _ where numCount > 0 && numCount < 10000:
            numStr = numCount.description
        case _ where numCount >= 10000:
            //判断能否被10000整除
            let numDouble: Double = Double(numCount) / 10000
            let numInt: Int = numCount / 10000
            let numDiff: Double = numDouble - Double(numInt)
            
            if numDiff >= 0 && numDiff < 0.1
            {
                numStr = String(format: "%d万", numInt)
            }
            else
            {
              numStr = String(format: "%.1f万", numDouble)
            }
        default:
            numStr = "error"
        }
        
        return numStr ?? "无"
    }
    
    //来源文字
    private func handleSourceTitle(title: String)
    {
        //截取
//        if title != ""
//        {
//            let sourceArray: [String] = title!.components(separatedBy: CharacterSet(charactersIn: "<>"))
//            sourceTitle = "来自: \(sourceArray[2])"
//        }
        
        if let startRange = title.range(of: "\">"), let endRange = title.range(of: "</")
        {
            let startIndex = startRange.upperBound
            let endIndex = endRange.lowerBound
            
            let result = title.substring(with: startIndex..<endIndex)
            sourceTitle = "来自: \(result)"
        }
    }
    
    //拼接转发微博内容
    private func handleRetweetContent(Content: String?, userName: String?)
    {
        if let contentText = Content,let name = userName
        {
            reweetContent = "@\(name): \(contentText)"
            //  处理转发微博富文本内容
            retweetAttributedText = handleOriginalAttributedText(originalText: reweetContent ?? "", isOriginal: false)
        }
        else
        {
            reweetContent = nil
        }
    }
    
    //根据认证等级 整型数据 处理认证等级图片
    private func handleVerifiedImage(verified: Int)
    {
        switch verified {
        case 0:
            verifiedImage = UIImage(named:"avatar_vip")
        case 2,3,5:
            verifiedImage = UIImage(named:"avatar_grassroot")
        case 220:
            verifiedImage = UIImage(named:"avatar_enterprise_vip")
        default:
            verifiedImage = nil
        }
    }
    
    //根据mbrank 整型数据处理等级图片
    private func handleMbrankImage(mbrnk: Int)
    {
        if mbrnk >= 1 && mbrnk <= 6
        {
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrnk)")
        }
    }
}
